import Globals from "./globals.min.js";

Globals.whenReady = (function () {
  //这个函数返回whenReady()函数
  var funcs = []; //当获得事件时，要运行的函数
  var ready = false; //当触发事件处理程序时,切换为true

  //当文档就绪时,调用事件处理程序
  function handler(e) {
    if (ready) return; //确保事件处理程序只完整运行一次

    //如果发生onreadystatechange事件，但其状态不是complete的话,那么文档尚未准备好
    if (e.type === "onreadystatechange" && document.readyState !== "complete") {
      return;
    }

    //运行所有注册函数
    //注意每次都要计算funcs.length
    //以防这些函数的调用可能会导致注册更多的函数
    for (var i = 0; i < funcs.length; i++) {
      funcs[i].call(document);
    }
    //事件处理函数完整执行,切换ready状态, 并移除所有函数
    ready = true;
    funcs = null;
  }
  //为接收到的任何事件注册处理程序
  if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", handler, false);
    document.addEventListener("readystatechange", handler, false); //IE9+
    window.addEventListener("load", handler, false);
  } else if (document.attachEvent) {
    document.attachEvent("onreadystatechange", handler);
    window.attachEvent("onload", handler);
  }
  //返回whenReady()函数
  return function whenReady(fn) {
    if (ready) {
      fn.call(document);
    } else {
      funcs.push(fn);
    }
  };
})();

Globals.supplementZero = function (num) {
  if (num.toString().length < 2) {
    return "0" + num;
  }
  return num.toString();
};

Globals.windowWidth = function(){
  return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
};

Globals.getWinScrollTop = function () {
  return (
    document.documentElement.scrollTop ||
    window.pageYOffset ||
    document.body.scrollTop
  );
};

Globals.getOffsetTopByBody = function (el) {
  var offsetTop = 0;
  var offsetLeft = 0;
  while (el && el.tagName !== "BODY") {
    offsetTop += el.offsetTop;
    offsetLeft += el.offsetLeft;
    el = el.offsetParent;
  }
  return { top: offsetTop, left: offsetLeft };
};

/**
 * 取消冒泡
 */
Globals.stopBubble = function (e) {
  if (e.stopPropagation) {
    e.stopPropagation();
  } else {
    e.cancelBubble = true;
  }
};

/**
 * 在规定时间内只触发一次
 * eg:
 * function fn() {console.log("节流");}
 * addEventListener("scroll", throttle(fn, 1000));
 */
Globals.throttle = function (fn, delay) {
  // 利用闭包保存时间
  let prev = Date.now();
  return function () {
    let context = this;
    let arg = arguments;
    let now = Date.now();
    if (now - prev >= delay) {
      fn.apply(context, arg);
      prev = Date.now();
    }
  };
};
